package com.wyman.factory.support;

import com.wyman.BeanException;
import com.wyman.factory.FactoryBean;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @Author 李伟民
 * @Description
 * @DateTime 2024/12/14 21:20
 */
//DefaultSingletonBeanRegistry管理容器中创建出来的bean
//FactoryBeanRegistrySupport 管理自定义的bean
public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry{

    private final Map<String,Object> factoryBeanObjectCache = new ConcurrentHashMap<>();

    public Object getCachedObjectFromFactoryBean(String beanName) {
        Object bean = this.factoryBeanObjectCache.get(beanName);
        return (bean==NULL_OBJECT)?null:bean;
    }

    //NULL_OBJECT作用是 判断这个beanName有没有之前被创建过 如果被创建过并且是null 那么将（beanName,NULL_OBJECT)存起来 后面在get时不会因为是null重新创建
    public Object getObjectFromFactoryBean(FactoryBean factory,String beanName){
        if(factory.isSingleton()){

            Object object = this.factoryBeanObjectCache.get(beanName);
            if(object == null){
                object = doGetObjectFromFactoryBean(factory,beanName);
                this.factoryBeanObjectCache.put(beanName,(object==null?NULL_OBJECT:object));
            }
            return (object==NULL_OBJECT)?null:object;

        }
        else {
            return doGetObjectFromFactoryBean(factory,beanName);
        }
    }

    private Object doGetObjectFromFactoryBean(FactoryBean factory,String beanName) {
        try {
            return factory.getObject();
        } catch (Exception e) {
            throw  new BeanException("FactoryBean threw exception on object[" + beanName + "] creation", e);
        }
    }


}
